<template>
  <div class="app-container">
    <el-dialog :title="title" :visible.sync="visible" width="1300px" append-to-body :close-on-click-modal="false">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="服务名" prop="serviceId">
          <el-select
            v-model="queryParams.serviceId"
            clearable
            filterable
            placeholder="请选择服务名"
            @keyup.enter.native="handleQuery"
          >
            <el-option
              v-for="item in serviceOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="链路ID" prop="traceId">
          <el-input v-model="queryParams.traceId" clearable placeholder="链路ID,仅支持精确查询" @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="处理人" prop="disposeUser">
          <el-input v-model="queryParams.disposeUser" clearable placeholder="缺陷处理人,支持模糊查询"
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="状态" prop="problemStatus">
          <el-select
            v-model="queryParams.problemStatus"
            clearable
            multiple
            placeholder="请选择缺陷状态"
            @change="val => handleStoreQueryParams(storeStatusKey, val)"
            @keyup.enter.native="handleQuery"
          >
            <el-option
              v-for="item in statusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="缺陷等级" prop="problemLevels">
          <el-select
            v-model="queryParams.problemLevels"
            clearable
            multiple
            placeholder="请选择缺陷等级"
            @change="val => handleStoreQueryParams(storeProblemLevelKey, val)"
            @keyup.enter.native="handleQuery"
          >
            <el-option
              v-for="item in problemLevelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="缺陷原因" prop="problemCauses">
          <el-select
            v-model="queryParams.problemCauses"
            clearable
            multiple
            placeholder="请选择缺陷原因"
            @change="val => handleStoreQueryParams(storeProblemCauseKey, val)"
            @keyup.enter.native="handleQuery"
          >
            <el-option
              v-for="item in problemCauseOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="记录时间" prop="recordTimes">
          <el-date-picker
            v-model="queryParams.recordTimes"
            clearable
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            placeholder="创建缺陷的时间"
            @change="val => handleStoreQueryParams(storeProblemTimesKey, val)"
            @keyup.enter.native="handleQuery"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="告警时间" prop="alarmTimes">
          <el-date-picker
            v-model="queryParams.alarmTimes"
            clearable
            type="datetimerange"
            :picker-options="pickerOptions"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            align="right"
            value-format="yyyy-MM-dd HH:mm:ss"
            format="yyyy-MM-dd HH:mm:ss"
            @change="val => handleStoreQueryParams(storeAlarmTimesKey, val)"
            @keyup.enter.native="handleQuery"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="problemList" ref="table"
                @selection-change="handleSelectionChange" @row-dblclick="handleSelection">
        <el-table-column v-if="queryParams.isView === false" type="selection" width="50" align="center"/>
        <el-table-column label="缺陷名称" align="center" :show-overflow-tooltip="true" prop="problemName"/>
        <el-table-column label="异常标识" align="center" prop="stackHash"/>
        <el-table-column label="所属服务" align="center" prop="serviceName"
                         :formatter="(row, column, cellValue, index) =>
                       `${row.serviceCnName ? row.serviceCnName:'unknown'}(${row.serviceZnName ? row.serviceZnName:'unknown'})`"
                         :show-overflow-tooltip="true" width="180"/>
        <el-table-column label="缺陷等级" align="center" prop="problemLevelText"/>
        <el-table-column label="缺陷原因" align="center" prop="problemCauseText"/>
        <el-table-column label="记录时间" align="center" prop="recordTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.recordTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="告警时间" align="center" prop="alarmTime" width="180">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.alarmTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="处理人" align="center" prop="disposeUserName"/>
        <el-table-column label="状态" align="center" prop="status"
                         :formatter="(row, column, cellValue, index) => {
                         let text = statusOptions.filter(e => e.value === row.status).map(e => e.label);
                         return text ? text : '';
                       }"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleView(scope.row)"
              v-hasPermi="['hawk-eye:problem-record:edit']"
            >查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="Number(total)>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <div v-if="queryParams.isView === false" slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <modal-form ref="modalForm" @submitted="getList"></modal-form>
  </div>
</template>

<script>
  import {repairProblemPage,dictListByType} from "@/api/hawkeye/problem";
  import {serviceNameList} from "@/api/hawkeye/service";
  import {formatDate} from "@/utils/index";
  import ModalForm from "@/views/hawkeye/problemrecord/modules/ModalForm";

  export default {
    name: "SelectAlarmLogTable",
    components: {
      ModalForm
    },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        selectedProblemList: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 【请填写功能名称】表格数据
        problemList: [],
        serviceOptions: [],
        problemLevelOptions: [],
        problemCauseOptions: [],
        statusOptions: [
          {
            label: "未解决",
            value: 0
          },
          {
            label: "已解决",
            value: 1
          },
          {
            label: "关闭",
            value: 2
          }
        ],
        pickerOptions: {
          shortcuts: [
            {
              text: '近一小时',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 1);
                picker.$emit('pick', [start, end]);
              }
            },
            {
              text: '近一天',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '近一周',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                picker.$emit('pick', [start, end]);
              }
            }, {
              text: '近一个月',
              onClick(picker) {
                const end = new Date();
                const start = new Date();
                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                picker.$emit('pick', [start, end]);
              }
            }]
        },
        // 弹出层标题
        title: "缺陷列表",
        // 是否显示弹出层
        visible: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          isView: true,
        },
        problemLevel: 'problemLevel',
        problemCause: 'problemCause',
        storeAlarmTimesKey: 'hawkEye:problemreocrd:alarmDatePicker',
        storeProblemTimesKey: 'hawkEye:problemreocrd:problemDatePicker',
        storeStatusKey: 'hawkEye:problemreocrd:problemStatus',
        storeProblemLevelKey: 'hawkEye:problemreocrd:problemLevel',
        storeProblemCauseKey: 'hawkEye:problemreocrd:problemCause'
      };
    },
    created() {
      this.initDatePicker();
    },
    methods: {
      initDatePicker() {
        let picker1 = localStorage.getItem(this.storeAlarmTimesKey);
        let now = new Date()
        if (picker1) {
          try {
            this.$set(this.queryParams, 'alarmTimes', [formatDate(new Date(now.getTime() - JSON.parse(time))), formatDate(now)])
          } catch (e) {
            localStorage.removeItem(this.storeAlarmTimesKey);
          }
        }
        let picker2 = localStorage.getItem(this.storeProblemTimesKey);
        if (picker2) {
          try {
            this.$set(this.queryParams,'recordTimes', [formatDate(new Date(now.getTime() - JSON.parse(time))), formatDate(now)])
          } catch (e) {
            localStorage.removeItem(this.storeProblemTimesKey);
          }
        }
        let statusAsString = localStorage.getItem(this.storeStatusKey);
        if (statusAsString) {
          try {
            this.$set(this.queryParams, 'problemStatus', JSON.parse(statusAsString))
          } catch (e) {
            localStorage.removeItem(this.storeStatusKey);
          }
        }
        let levelAsString = localStorage.getItem(this.storeProblemLevelKey);
        if (levelAsString) {
          try {
            this.$set(this.queryParams, 'problemLevels', JSON.parse(levelAsString))
          } catch (e) {
            localStorage.removeItem(this.storeProblemLevelKey);
          }
        }
        let causeAsString = localStorage.getItem(this.storeProblemCauseKey);
        if (causeAsString) {
          try {
            this.$set(this.queryParams, 'problemCauses', JSON.parse(causeAsString))
          } catch (e) {
            localStorage.removeItem(this.storeProblemCauseKey);
          }
        }
      },
      open(repairId, isView) {
        this.visible = true;
        this.queryParams.isView = isView;
        this.queryParams.repairId = repairId;
        this.getServiceNameList();
        this.getProblemLevelList();
        this.getProblemCauseList();
        this.getList();
      },
      getServiceNameList() {
        serviceNameList().then(res => {
          this.serviceOptions = res.data;
        })
      },
      getProblemLevelList() {
        dictListByType(this.problemLevel).then(res => {
          this.problemLevelOptions = res.data;
        })
      },
      getProblemCauseList() {
        dictListByType(this.problemCause).then(res => {
          this.problemCauseOptions = res.data;
        })
      },
      togCheck(row) {
        if (row) {
          this.$refs.table.toggleRowSelection(row, true);
        }
      },
      /** 查询【请填写功能名称】列表 */
      getList() {
        this.loading = true;
        repairProblemPage(this.queryParams).then(res => {
          this.problemList = res.records || [];
          this.total = res.total;
          this.loading = false;
          this.$nextTick(() => {
            this.problemList.forEach(e => {
              if (e.firstProblem && e.firstProblem == 1){
                this.togCheck(e);
              }
            });
          })
        });
      },
      // 取消按钮
      cancel() {
        this.visible = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.problemList = []
        this.queryParams.isView = true;
        this.$refs.table.clearSelection();
      },
      /** 修改按钮操作 */
      handleView(row) {
        this.$refs.modalForm.open(row, true);
      },
      handleStoreQueryParams(key, value) {
        if (value) {
          localStorage.setItem(key, JSON.stringify(value));
        } else {
          localStorage.removeItem(key);
        }
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.selectedProblemList = selection
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      handleSelection(row, column, event){
        const table = this.$refs.table;
        const selection = table.store.states.selection.includes(row);
        if (selection) {
          table.toggleRowSelection(row, false);
        } else {
          table.toggleRowSelection(row, true);
        }
      },
      /** 提交按钮 */
      submitForm() {
        if (!this.selectedProblemList) {
          this.$modal.msgWarning("请至少选择一条数据！！！")
          return
        }
        this.visible = false
        this.$emit('submitted', this.selectedProblemList)
      }
    }
  };
</script>
